import {Billboard, Image, Text} from '@react-three/drei'
import {CarSwitcher} from './CarSwitcher.jsx'
import {degToRad} from 'three/src/math/MathUtils.js'
import {useAtom} from 'jotai'
import {ShowNameEditAtom} from '../UI.jsx'

export const CarBillboard = ({player, user, ...props}) => {

  const [showNameEdit, setShowNameEdit] = useAtom(ShowNameEditAtom)

  return (
    <>
      <Billboard position-y={2.1} position-x={0.5}>
        <Text fontSize={0.34} anchorX={'right'}>
          {player.state.name || player.state.profile.name}
          <meshBasicMaterial color="white"/>
        </Text>
        <Text
          fontSize={0.34}
          anchorX={'right'}
          position-x={0.02}
          position-y={-0.02}
          position-z={-0.01}
        >
          {player.state.name || player.state.profile.name}
          <meshBasicMaterial color="black" transparent opacity={0.8}/>
        </Text>
        {player.id === user && (
          <>
            <Image
              onClick={() => setShowNameEdit(true)}
              position-x={0.2}
              scale={0.3}
              url="images/edit.png"
              transparent
            />
            <Image
              position-x={0.2 + 0.02}
              position-y={-0.02}
              position-z={-0.01}
              scale={0.3}
              url="images/edit.png"
              transparent
              color="black"
            />
          </>
        )}
      </Billboard>
      <group position-y={player.id === user ? 0.15 : 0}>
        <CarSwitcher player={player}/>
      </group>

      {player.id === user && (
        <>
          <pointLight
            position-x={1}
            position-y={2}
            intensity={2}
            distance={3}
          />
          <group rotation-x={degToRad(-90)} position-y={0.01}>
            <mesh receiveShadow>
              <circleGeometry args={[2.2, 64]}/>
              <meshStandardMaterial
                color="pink"
                toneMapped={false}
                emissive={'pink'}
                emissiveIntensity={1.2}
              />
            </mesh>
          </group>
          <mesh position-y={0.1} receiveShadow>
            <cylinderGeometry args={[2, 2, 0.2, 64]}/>
            <meshStandardMaterial color="#8572af"/>
          </mesh>
        </>
      )}
    </>
  )
}
